package com.xiaozhen.jt809.adapter;

import com.xiaozhen.jt809.constant.JT809BusinessConstant;
import com.xiaozhen.jt809.domain.JT809MessageInfo;
import com.xiaozhen.jt809.service.MsgHandleService;
import com.xiaozhen.jt809.utils.ResponseUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/15 11:33
 * @description:
 */
@Slf4j
@Service
@ChannelHandler.Sharable
public class MyClientChannelHandlerAdapter extends ChannelHandlerAdapter {

    @Autowired
    private MsgHandleService msgHandleService;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.info("--- [发生异常] 释放资源: {}", cause.getMessage());
        // todo
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        JT809MessageInfo messageInfo = msgHandleService.getMessageInfo(ctx, "发起从链路链接请求");
        byte[] verifyCode = new byte[4];
        JT809MessageInfo responseMessage = ResponseUtil.responseMessage(messageInfo,
                JT809BusinessConstant.DOWN_CONNECT_REQ,
                verifyCode);
        ctx.writeAndFlush(responseMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        msgHandleService.handleMessage("从链路", ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    /**
     * 用于捕获事件（未在指定时间内向服务器发送数据）,发送一个心跳包。
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {
                // 发送心跳  保持链接
                JT809MessageInfo messageInfo = msgHandleService.getMessageInfo(ctx, "从链路连接保持请求");
                JT809MessageInfo responseMessage = ResponseUtil.responseMessage(messageInfo,
                        JT809BusinessConstant.DOWN_LINKTEST_REQ,
                        new byte[0]);
                ctx.writeAndFlush(responseMessage);
            } else if (state == IdleState.READER_IDLE) {
                // 3分钟内没有收到回应消息
                log.info("3分钟内没有收到回应消息，主动断开连接");
                ctx.disconnect();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

}
